import java.util.Deque;
import java.util.LinkedList;

public class Main {
    public static void main(String[] args) {
        int[] arr = {0,1,0,2,1,0,1,3,2,1,2,1};
        //int method = method(arr);
        int method2 = method2(arr);
        System.out.println(method2);
    }


    public static int method(int[] height) {
        Deque<Integer> stack = new LinkedList<Integer>();
        int ans = 0;
        int n = height.length;
        for (int i = 0; i < n; ++i) {
            while (!stack.isEmpty() && height[i] > height[stack.peek()]) {
                int top = stack.pop();
                if (stack.isEmpty()) {
                    break;
                }
                int left = stack.peek();
                int currWidth = i - left - 1;
                int currHeight = Math.min(height[left], height[i]) - height[top];
                ans += currWidth * currHeight;
            }
            stack.push(i);
        }
        return ans;
    }

    public static int method2(int[] height) {
        Deque<Integer> stack = new LinkedList<>();
        int area = 0;
        int n = height.length;
        for(int i = 0; i < n; ++i) {
            while(!stack.isEmpty() && height[i] > height[stack.peek()]) {
                int top = stack.pop();
                if(stack.isEmpty()) {
                    break;
                }
                int left = stack.peek();
                //求宽
                int curWidth = i - left -1;
                //求高
                int curHeight = Math.min(height[left], height[i] - height[top]);
                area += curWidth * curHeight;
            }
            stack.push(i);
        }
        return area;
    }
}